import 'dart:io';
import 'dart:typed_data';

import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_app_open_camera/page/test_img_page.dart';
import 'package:flutter_app_open_camera/resource/theme/dark_mode_provider.dart';
import 'package:flutter_app_open_camera/utils/loading_utils.dart';
import 'package:flutter_app_open_camera/utils/route_utils.dart';

import 'package:photo_manager/photo_manager.dart';

import 'package:pull_to_refresh/pull_to_refresh.dart';

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage>
    with WidgetsBindingObserver, SingleTickerProviderStateMixin {
  @override
  void initState() {
    super.initState();
    Loading.ctx = context;
    WidgetsBinding.instance.addObserver(this);
    _initAsync();
    Future.delayed(Duration(milliseconds: 100), () {
      // controller.callRefresh();
      _refreshController.requestRefresh();
    });
  }

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  bool first = true;

  // EasyRefreshController controller = new EasyRefreshController();

  int page = 0;

  int index = 0;
  int pageSize = 60;

  Future<void> _getData() async {
    var result = await PhotoManager.requestPermission();
    if (result) {
      page++;
      index = 0;
      List<AssetPathEntity> list =
          await PhotoManager.getAssetPathList(type: RequestType.image);
      List<AssetEntity> a = await list[0].getAssetListPaged(page, pageSize);
      if (a.length == 0) {
        _refreshController.loadNoData();
        return;
      }
      for (int i = 0; i < a.length; i++) {
        AssetEntity element = a[i];
        Uint8List thumb = await element.thumbData;
        File file = await element.file;
        data.add(AlbumData(thumb, file));
        if (i == a.length - 1) {
          setState(() {
            _refreshController.refreshCompleted();
            _refreshController.loadComplete();
          });
        }
      }
    }
  }

  Future<void> _refresh() async {
    var result = await PhotoManager.requestPermission();
    if (result) {
      page = 0;
      data.clear();

      index = 0;
      List<AssetPathEntity> list =
          await PhotoManager.getAssetPathList(type: RequestType.image);
      List<AssetEntity> a = await list[0].getAssetListPaged(page, pageSize);
      if (a.length == 0) {
        _refreshController.loadNoData();
        return;
      }
      for (int i = 0; i < a.length; i++) {
        AssetEntity element = a[i];
        Uint8List thumb = await element.thumbData;
        File file = await element.file;
        data.add(AlbumData(thumb, file));
        if (i == a.length - 1) {
          setState(() {
            _refreshController.refreshCompleted();
            _refreshController.loadComplete();
          });
        }
      }
      // success
    }
  }

  Future<void> _initAsync() async {
    await SpUtil.getInstance();
    setTheme(context);
  }

  @override
  void didChangePlatformBrightness() {
    super.didChangePlatformBrightness();
    // 设置初始化主题颜色
    setTheme(context);
  }

  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  Widget _itemBuilder(int index) {
    return InkWell(
      onTap: () {
        launch(context, TestImgPage(data: data, index: index),
            translation: true);
      },
      child: Hero(
        tag: index,
        child: FadeInImage(
          fadeInDuration: Duration(milliseconds: 200),
          fadeOutDuration: Duration(milliseconds: 200),
          width: double.infinity,
          height: double.infinity,
          placeholder: AssetImage('assets/images/pic.webp'),
          image: MemoryImage(data[index].thumb),
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  List<AlbumData> data = [];

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text('Stepper Demo'),
      ),
      body: Align(
          alignment: Alignment.topCenter,
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: SmartRefresher(
              enablePullDown: true,
              enablePullUp: true,
              controller: _refreshController,
              onRefresh: _refresh,
              onLoading: _getData,
              child: GridView.builder(
                  itemCount: data.length,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      mainAxisSpacing: 5,
                      crossAxisSpacing: 5),
                  itemBuilder: (BuildContext context, int index) {
                    return _itemBuilder(index);
                  }),
            ),
          )),
    );
  }
}

class AlbumData {
  Uint8List thumb;
  File file;
  bool ready;

  AlbumData(this.thumb, this.file, {this.ready = false});
}
